namespace AltNetUK.Models.Inputs
{
    using System;
    using System.Globalization;
    using System.Text.RegularExpressions;
    using SimpleWebServices.Data;

    public sealed class EmailValidator : RegexValidator
    {
        private static readonly Regex _expression = new Regex(@"^([a-zA-Z0-9_\+\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");

        public EmailValidator()
            : base(_expression, true)
        {
        }

        public override ValidationResult Validate(string text)
        {
            ValidationResult result = base.Validate(text);
            if (result.IsValid)
            {
                string xpath = string.Format(CultureInfo.InvariantCulture, "/registration[@complete=\"true\"][@email=\"{0}\"]", text);
                if (0 != Repository.Query<Registration>(xpath).Count)
                {
                    result.Errors.Add("is already registered");
                }
            }

            return result;
        }
    }
}